package hello;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import persistence.HibernateUtil;
import auction.chapter08.UserProcedure;

public class HelloWorldProcedure
{
	public static void main(String[] args)throws Exception{
		//test1();
		exeNamedQuery();
		//jdbcProcedure();
	}
	
	public static void jdbcProcedure()throws Exception{
		Session s1=HibernateUtil.getSessionFactory().openSession();
		Connection con=s1.connection();
		CallableStatement call=con.prepareCall("call getUser(1)");
		ResultSet rs=call.executeQuery();
		while(rs.next()){
			out(rs.getString("username"));
		}
		s1.close();
	}
	
	public static void exeNamedQuery()throws Exception{
		Session s1=HibernateUtil.getSessionFactory().openSession();
		Transaction tx1=s1.beginTransaction();
		
		Query q=s1.getNamedQuery("loadUserProcedure");
		q.setParameter(0, 1L);//numbered from 0.
		List<UserProcedure> r= q.list();
		out(r.get(0).getName()+"<-->"+r.get(0).getNotmapped());
		
		tx1.commit();
		s1.close();
	}
	
	public static void test1()throws Exception{
		Session s=HibernateUtil.getSessionFactory().openSession();
		Transaction tx=s.beginTransaction();
		
		Message m=new Message();
		m.setText("xx");
		out("xxx:"+s.save(m).getClass().getName());
		
		UserProcedure u=new UserProcedure();
		u.setName("wei wei");
		u.setAddress("second ring road");
		//out(s.save(u));
		
		tx.commit();
		s.close();
		
		
		
		Session s1=HibernateUtil.getSessionFactory().openSession();
		Transaction tx1=s1.beginTransaction();
		
		UserProcedure loadu=(UserProcedure)s1.load(UserProcedure.class, 1L);
		out(loadu.getName());
		out(loadu.getNotmapped());
		
		/*
		UserProcedure loadu=(UserProcedure)s1.load(UserProcedure.class, 1L);
		s1.delete(loadu);
		*/
		
		/*
		UserProcedure n=new UserProcedure();
		n.setId(1L);
		s1.delete(n);
		*/
		tx1.commit();
		s1.close();
		
		
		
		//HibernateUtil.stat();
		HibernateUtil.shutdown();
		
		//out(loadu.getId()+" "+loadu.getName());
	}
	
	public static void getParent(Class clazz)
	{
		Class parent=clazz.getSuperclass();
	  if(parent !=null)
	  {
			System.out.println("###"+parent.getName());
			getParent(parent);
		}
	}
	
	static void out(Object obj)
	{
		System.out.println("--->"+obj);
	}
}
